<template>
  <div class="container">
    <div v-show="ifShow">
      <calendar lunar="true" @select="select"></calendar>
    </div>
    <header class="d-flex space-between middle">
      <div class="left d-flex middle eject-calendar" @click="showCalendar"> 
        <span>{{ calendar.date }}</span>
        <i class="iconfont icon-rili"></i>
      </div>
      <div class="right">
        <span>农历 {{ calendar.lunar }}</span>
      </div>
    </header>
    <div class="selectCity d-flex">
      <div class="right d-flex column space-around">
        <div class="d-flex middle">
          <picker mode="region" :value="region" @change="bindRegionChange" class="region">
            <p>{{ region[1] }}
              <text class="iconfont icon-zhuanhuan"></text>
            </p>
          </picker>
          <span>{{ temperature }}℃</span>          
        </div>
        <p>{{ weather }}</p>
      </div>
      <div class="left d-flex bottom column space-around suit-avoid" @click="toLuck">
        <p class="suit">{{ calendar.suit }}<span>宜</span></p>
        <p class="avoid">{{ calendar.avoid }}<span>忌</span></p>
      </div>
    </div>
    <!-- 今日良言 -->
    <div class="today" :style="{backgroundImage: 'url(' + picUrl + ')', backgroundSize:'cover'}" @click="detail">
      <p id="today-words">{{ message }}​​​​</p>
      <div class="share-today-words d-flex flex-end">
        <button open-type="share" id="share-today-words" plain @click.stop="stop">
          <text class="iconfont icon-weixin"></text>
          <text>分享</text>
        </button>
        <!-- <button @click="share">
          <i class="iconfont icon-pengyouquan"></i>
        </button> -->
        <!-- <canvas class=".canvas" canvas-id="myCanvas" style="width:100%;height:568px;"></canvas> -->
      </div>
    </div>
    <!-- 广告位 -->
    <div style="padding: 0 10px;" v-show="showAd">
      <ad unit-id="adunit-98d66e99291778e5" @error="adError"></ad>
    </div>
    <!-- 历史的今天 -->
    <history-today :selectedDate="selectDate" :resetTabHeight="ifShow"></history-today>
  </div>
</template>
<script>
import Calendar from 'mpvue-calendar'
import 'mpvue-calendar/src/style.css'
import HistoryToday from '../../components/HistoryToday'

export default {
  components: {
    Calendar,
    HistoryToday
  },
  data () {
    return {
      calendar: {
        date: '',
        lunar: '',
        suit: '',
        avoid: ''
      },
      picUrl: '', // 背景图片
      selectDate: '', // 选择日历日期
      message: '',
      ifShow: false,
      region: [],
      temperature: '',
      weather: '',
      today_words: '',
      list: [],
      qr_code: '',
      windowWidth: 320,
      showAd: true
    }
  },
  // 微信分享
  onShareAppMessage (res) {
    if (res.from === 'menu') {
      return {
        title: '历史持续发生，这里有你不知道的',
        path: '/pages/index/main'
      }
    }
    return {
      title: this.message,
      path: '/pages/index/main',
      imageUrl: this.picUrl
    }
  },
  onLoad () {
    this.getCurrentCity()
    this.getCalendar()
  },
  methods: {
    adError () {
      this.showAd = false
    },
    // 获取万年历信息
    getCalendar () {
      this.$http.get({
        url: this.$services.GET_CALENDAR_ALL,
        data: {}
      }).then(res => {
        if (res.code === 0) {
          this.calendar = res.body.calendar
          // this.calendar.date = this.calendar.date.replace(/-/g, '.')
          this.calendar.suit = this.calendar.suit.split('.').slice(0, 3).join(' ')
          this.calendar.avoid = this.calendar.avoid.split('.').slice(0, 3).join(' ')
          this.message = res.body.message.message.slice(0, 100)
          this.today_words = res.body.message.content
          this.picUrl = res.body.message.picUrl || 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564548356828&di=a72f33c671903968c297165381fc9364&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201701%2F13%2F20170113092725_AucYf.jpeg'
        }
      })
    },
    // 选择日历时间
    select (e) {
      this.selectDate = e.join('-')
      this.calendar.date = this.selectDate
      this.getDateInfo()
      this.ifShow = false
      wx.reportAnalytics('click_on_select_date', {
      })
    },
    // 获取日历信息
    getDateInfo (e) {
      this.$http.get({
        url: this.$services.GET_CALENDAR,
        data: {
          d: this.selectDate
        }
      }).then(res => {
        if (res.code === 0) {
          this.calendar = res.body
          this.calendar.suit = this.calendar.suit.split('.').slice(0, 3).join(' ')
          this.calendar.avoid = this.calendar.avoid.split('.').slice(0, 3).join(' ')
        }
      })
    },
    // 阻止冒泡
    stop () {
      wx.navigateTo({
        url: '/pages/index/main'
      })
    },
    // 跳转到黄历页面
    toLuck () {
      wx.switchTab({
        url: '/pages/calendar/main'
      })
      wx.setStorageSync('likeType', '0')
    },
    // 获取用户当前所在城市
    getCurrentCity () {
      wx.showLoading({
        title: '加载中'
      })
      wx.request({
        url: 'https://apis.map.qq.com/ws/location/v1/ip',
        method: 'GET',
        data: {
          key: '4S4BZ-B7WRX-WRV44-TSPQ7-L23Y5-MOBRI'
        },
        success: res => {
          if (res.data.status === 0) {
            const info = res.data.result.ad_info
            this.region = [info.province, info.city, info.district]
            this.getWeather()
          }
        }
      })
    },
    // 获取天气信息
    getWeather () {
      wx.request({
        url: 'https://www.apiopen.top/weatherApi',
        method: 'GET',
        data: {
          city: this.region[1]
        },
        success: res => {
          if (res.data.code === 200) {
            this.temperature = res.data.data.wendu
            this.weather = res.data.data.forecast[0].type
            wx.hideLoading()
          }
        }
      })
    },
    // 切换日历显隐
    showCalendar () {
      this.ifShow = !this.ifShow
    },
    // 选择所在地区
    bindRegionChange (e) {
      this.region = e.target.value
      this.getWeather()
    },
    // 今日良言详情
    detail () {
      if (this.today_words !== '') {
        wx.setStorageSync('todayWords', this.today_words)
        wx.navigateTo({
          url: '/pages/today_words/main'
        })
      }
    },
    // 分享到朋友圈
    share () {
      wx.downloadFile({
        url: 'http://d.gionee.com/nav/20190802/lockimage/20190802/1564732923211.jpg',
        success: res => {
          this.qr_code = res.tempFilePath
          this.drawImage()
          setTimeout(() => {
            this.canvasToImage()
          }, 200)
        }
      })
    },
    // 绘制图片
    drawImage () {
      // 绘制canvas图片
      // var that = this
      const ctx = wx.createCanvasContext('myCanvas')
      var bgPath = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564743293372&di=d249548547907de019cca2505ce6521a&imgtype=0&src=http%3A%2F%2Fgss0.baidu.com%2F7Po3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2Fd009b3de9c82d1581bc3a16e840a19d8bd3e42a8.jpg'
      // var portraitPath = that.data.portrait_temp
      // var hostNickname = '云淡风轻'

      var qrPath = this.qr_code
      var windowWidth = this.windowWidth
      // that.setData({
      //   scale: 1.6
      // })
      // 绘制背景图片
      ctx.drawImage(bgPath, 0, 0, 300, 500)

      // 绘制头像
      // ctx.save()
      // ctx.beginPath()
      // ctx.arc(windowWidth / 2, 0.32 * windowWidth, 0.15 * windowWidth, 0, 2 * Math.PI)
      // ctx.clip()
      // ctx.drawImage(portraitPath, 0.7 * windowWidth / 2, 0.17 * windowWidth, 0.3 * windowWidth, 0.3 * windowWidth)
      // ctx.restore()
      // 绘制第一段文本
      ctx.setFillStyle('#ffffff')
      ctx.setFontSize(0.037 * windowWidth)
      ctx.setTextAlign('center')
      ctx.fillText(' 长按二维码保存图片分享到朋友圈', windowWidth / 2, 0.52 * windowWidth)
      // 绘制第二段文本
      // ctx.setFillStyle('#ffffff')
      // ctx.setFontSize(0.037 * windowWidth)
      // ctx.setTextAlign('center')
      // ctx.fillText('邀请你一起来领券抢红包啦~', windowWidth / 2, 0.57 * windowWidth)
      // 绘制二维码
      ctx.drawImage(qrPath, 0.64 * windowWidth / 2, 0.75 * windowWidth, 0.36 * windowWidth, 0.36 * windowWidth)
      // 绘制第三段文本
      // ctx.setFillStyle('#ffffff')
      // ctx.setFontSize(0.037 * windowWidth)
      // ctx.setTextAlign('center')
      // ctx.fillText('长按二维码领红包', windowWidth / 2, 1.36 * windowWidth)
      ctx.draw()
    },
    canvasToImage () {
      // var that = this
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.windowWidth,
        height: this.windowWidth * 1.6,
        destWidth: this.windowWidth * 4,
        destHeight: this.windowWidth * 4 * 1.6,
        canvasId: 'myCanvas',
        success: function (res) {
          console.log('朋友圈分享图生成成功:' + res.tempFilePath)
          wx.previewImage({
            current: res.tempFilePath, // 当前显示图片的http链接
            urls: [res.tempFilePath] // 需要预览的图片http链接列表
          })
        },
        fail: function (err) {
          console.log('失败')
          console.log(err)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  header {
    padding: 5px 10px;
    font-weight: bold;
    .left {
      .iconfont {
        font-size: 20px;
        font-weight: normal;
        margin-left: 5px;
      }
    }
  }
  .selectCity {
    padding: 5px 10px 10px;
    .left {
      flex: 1;
      font-size: 15px;
      font-weight: bold;
      white-space: nowrap;
      .common {
        color: #fff;
        padding: 2px 5px;
        border-radius: 5px;
        font-size: 14px;
        margin-left: 5px;
      }
      .suit {
        color: #6ba366;
        // margin: 6px 0;
        span {
          background: #6ba366;
          @extend .common;
        }
      }
      .avoid {
        color: #ba6749;
        // margin: 6px 0;
        span {
          background: #ba6749;
          @extend .common;
        }
      }
    }
    .right {
      flex: 1;
      font-size: 18px;
      span {
        margin-left: 10px;
        font-size: 20px;
      }
    }
  }
  .today {
    height: 150px;
    padding: 10px 0;
    border-radius: 10px;
    margin: 10px;
    position: relative;
    p {
      color: #fff;
      position: absolute;
      bottom: 10px;
      font-size: 16px;
      padding: 0 10px;
      text-align: justify;
    }
    .share-today-words {
      position: absolute;
      top: 5px;
      right: 10px;
      button {
        border: none;
        color: #fff;
        padding: 0;
        line-height: 1;
        text {
          font-size: 16px;
          margin: 0 5px;
        }
      }
      .canvas {
        width: 100%;
        position: fixed;
        left: 0;
        top: 999999px;
      }
    }
  }
}
</style>

